package com.wthink.hzgj.service

import com.alibaba.fastjson.JSON
import com.wthink.hzgj.busInfo.BusInfo
import com.wthink.hzgj.busplan.data.BusPlan
import com.wthink.hzgj.data.BusRepository
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.data.domain.*
import com.wthink.hzgj.data.repository.DefaultBusRepository
import com.wthink.hzgj.service.jt808.*
import com.wthink.hzgj.util.Log
import com.wthink.hzgj.wireless.Wireless
import com.wthink.newMain.data.*
import com.wthink.newMain.settings.config.inner.netconfig.adapter.NetConfig
import com.wthink.newMain.settings.config.inner.netconfig.adapter.NetConfigInfo
import com.wthink.ubus.UResult
import com.wthink.ubus.Ubus
import com.wthink.ubus.server.Subscriber
import connectableflow.publish
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*

object DevService {

    val devStateFlow: Flow<DevState>
    val jt808Flow: Flow<JT808Message>
    val gpsFlow: Flow<Location>

    val busRepository: BusRepository = DefaultBusRepository()

    init {

        Ubus.load("10.0.0.2:6791")
        val busFlow = callbackFlow {
            Ubus.registerSubscriber(Subscriber("bus") { method: String, payload: String ->
                when (method) {
                    "state" -> {
                        offer(MessageHelp.parseDevState(payload))
                    }
                    "rec808" -> {
                        val bus808 = MessageHelp.parse808(payload)
                        JT808Help.decode(bus808.type, bus808.payload)?.let {
                            offer(it)
                        }
                    }
                }
            })
            awaitClose { }
        }.publish().apply { connect(GlobalScope) }

        // 设备状态通知
        devStateFlow = (busFlow as Flow<*>).filter { it is DevState } as Flow<DevState>

        //808消息通知
        jt808Flow = (busFlow as Flow<*>).filter { it is JT808Message } as Flow<JT808Message>

        //GPS状态通知
        gpsFlow = callbackFlow<Location> {
            Ubus.registerSubscriber(Subscriber("gpsd") { method: String, payload: String ->
                when (method) {
                    "location" -> {
                        offer(MessageHelp.parseGps(payload))
                    }
                }
            })
            awaitClose { }
        }.publish().apply { connect(GlobalScope) }
        Ubus.registeProvider(ScreenProvider.toUbusProvider())
    }

    /**
     * 查询线路的站点信息
     */
    suspend fun getLineDetail(line: String): Result<LineStation> {
        val ubusRet = Ubus.invoke("bus", "query_line_detail", "{\"line\":\"${line}\"}")
        if (!ubusRet.success) {
            Log.debug("查询线路 ${line} 站点信息失败.${ubusRet.err}")
            return Result.Error(RuntimeException(ubusRet.err))
        }

        Log.debug("线路: ${line},站点信息:${ubusRet.rsp}")
        return Result.Success(MessageHelp.parseLineStation(ubusRet.rsp!!))
    }

    /**
     * 查询所有线路
     */
    suspend fun getLineList(): Result<List<Line>> {
        val ubusRet = Ubus.invoke("bus", "query_line_list", "{}")
        if (!ubusRet.success) {
            Log.debug("查询线路失败.${ubusRet.err}")
            return Result.Error(RuntimeException(ubusRet.err))
        }

        Log.debug("线路: ${ubusRet.rsp}")
        return Result.Success(MessageHelp.parseLineList(ubusRet.rsp!!))
    }

    /**
     * 请求语音报站
     */
    suspend fun stationVoice(line: String, stationId: String, arrive: Boolean): Result<Boolean> {
        val type = if (arrive) {
            1
        } else {
            2
        }
        val ubusRet = Ubus.invoke(
            "bus",
            "req_voice_station",
            "{\"line\":\"${line}\",\"station\":\"${stationId}\",\"type\":\"${type}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(true)
        }

        Log.debug("报站失败.line: ${line}, station: ${stationId}, arrive: ${arrive}")
        return Result.Success(false)
    }

    /**
     * 考勤
     */
    suspend fun checkin(line: String, user: String, type: CheckinType): Result<String?> {
        val lineId = if (line.isEmpty()) {
            0
        } else {
            line.toInt()
        }
        val ubusRet = send808("0b05", JT808Help.encode(JT_0B05(lineId, user, type)))
        if (ubusRet.success) {
            val actRet = MessageHelp.parseActRet(ubusRet.rsp!!)
            if (actRet.success) {
                return Result.Success(null)
            } else {
                return Result.Error(java.lang.RuntimeException("${actRet.err}"))
            }
        }
        Log.debug("考勤失败. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException("考勤失败:${ubusRet.err}"))
    }

    suspend fun queryCamera(): Result<CameraInfo> {
        val ubusRet = Ubus.invoke(
            "camera",
            "query_camera",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseCameraInfo(ubusRet.rsp!!))
        }

        Log.debug("查询摄像头失败. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    suspend fun setCamera(cameras: List<String>): Result<List<String>> {
        val ubusRet = Ubus.invoke(
            "camera",
            "req_camera",
            "{\"video\":${JSON.toJSON(cameras)}}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseVideoList(ubusRet.rsp!!))
        }

        Log.debug("设置摄像头失败. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    suspend fun queryAppVer(): Result<AppverInfo> {
/*
       if (2 > 1) {
            return Result.Error(RuntimeException("not call"))
        }
*/
        val ubusRet = Ubus.invoke(
            "bus",
            "req_upgrade",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseAppverInfo(ubusRet.rsp!!))
        }
        Log.debug("查询app版本失败. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * 监听GPS信息
     */
    suspend fun listenGps(): Flow<Location> {
        return gpsFlow
    }

    /**
     * 监听主机状态信息
     */
    suspend fun listenDevState(): Flow<DevState> {
        android.util.Log.d("devStateFlow", "devStateFlow执行了")
        return devStateFlow
    }

    /**
     * 监听车辆状态信息
     */
    suspend fun listenBusState(): Flow<BusStateA> {
        return jt808Flow.filter {
            it is JT_0B02
        }.map {
            val jt0b02 = it as JT_0B02
            val updir = jt0b02.ywlx == 1
            val arriveOrLeaving = jt0b02.arriveOrLeaving == 1
            val line = busRepository.findLineById(jt0b02.line)
            val stationList = busRepository.getStationList(jt0b02.line, updir)

            if (line == null || stationList.isEmpty() || stationList.size < jt0b02.stationIndex) {
                null
            } else {
                BusStateA(
                    jt0b02.line,
                    line.name,
                    stationList[jt0b02.stationIndex].station,
                    stationList[jt0b02.stationIndex].name,
                    updir, it.arriveOrLeaving.toString()
                )
            }
        }.filterNotNull()
    }


    /**
     * 监听车辆状态信息
     */
    suspend fun listenSpeedLimit(): Flow<String> {
        return jt808Flow.filter {
            it is JT_5000
        }.map {
            val jt8b09 = it as JT_5000
            val speedMsg = jt8b09.speedMsg
            speedMsg
        }.filterNotNull()
    }

    /**
     * 监听排班应答
     */
    suspend fun listenSchedleRefuse(): Flow<String> {
        return jt808Flow.filter {
            it is JT_8B09
        }.map {
            val jt8b09 = it as JT_8B09
            val refuse = jt8b09.isRefuse
            refuse
        }.filterNotNull()
    }

    /**
     * 监听平台消息
     */
    suspend fun listenBusNotice(): Flow<BusNotice> {
        return jt808Flow.filter {
            it is JT_8300
        }.map {
            val jt8300 = it as JT_8300
            val notice = jt8300.notice
            if (notice == null) {
                null
            } else {
                BusNotice(notice)
            }
        }.filterNotNull()
    }

    /**
     * 监听平台消息
     */
    suspend fun listen8B03(): Flow<String> {
        return jt808Flow.filter {
            it is JT_8B03
        }.map {
            val JT_8B03 = it as JT_8B03
            ""
        }.filterNotNull()
    }

    /**
     * 监听人脸识别
     */
    suspend fun listenFace(): Flow<FaceRec> {
        return jt808Flow.filter {
            it is JT_4600
        }.map {
            val jt4600 = it as JT_4600
            val faced = jt4600.isFaced
            if (faced == null) {
                null
            } else {
                FaceRec(faced)
            }
        }.filterNotNull()
    }

    /**
     * 监听 usb
     */
    suspend fun listenUsb(): Flow<USBadded> {
        return jt808Flow.filter {
            it is JT_4800
        }.map {
            val jt4800 = it as JT_4800
            val usbAdded = jt4800.isUSBadded
            if (usbAdded == null) {
                null
            } else {
                USBadded(usbAdded)
            }
        }.filterNotNull()
    }

    /**
     * 监听 进度
     */
    suspend fun listenProcess(): Flow<CopyProcess> {
        return jt808Flow.filter {
            it is JT_4801
        }.map {
            val jt4801 = it as JT_4801
            val process = jt4801.process
            if (process == null) {
                null
            } else {
                CopyProcess(process)
            }
        }.filterNotNull()
    }

    suspend fun listenBusDispatch(): Flow<BusDispatch> {
        // (it is JT_8B07 && it.queueSize > 0) ||
        return jt808Flow.filter { it is JT_8B01 }.map {
            val busDispatch = BusDispatch()
            if (it is JT_8B01) {
                busDispatch.line = it.line
                busDispatch.ccbh = it.ccbh
                busDispatch.clbh = it.clbh
                busDispatch.ddlx = it.ddlx
                busDispatch.driverId = it.driverId
                busDispatch.driverName = it.driverName
                busDispatch.endStationId = it.endStationId
                busDispatch.endStationName = it.endStationName
                busDispatch.endTime = it.endTime
                busDispatch.roadCard = it.roadCard
                busDispatch.startStationId = it.startStationId
                busDispatch.startStationName = it.startStationName
                busDispatch.startTime = it.startTime
                busDispatch.fjnr = it.fjnr
                busDispatch.time = it.time
                busDispatch.ywlx = it.ywlx
            } /*else if (it is JT_8B07) {
                busDispatch.line = it.line
                busDispatch.ccbh = it.ccbh
                busDispatch.clbh = it.clbh
                busDispatch.ddlx = it.ddlx
                busDispatch.driverId = it.driverId
                busDispatch.driverName = it.driverName
                busDispatch.endStationId = it.endStationId
                busDispatch.endStationName = it.endStationName
                busDispatch.endTime = it.endTime
                busDispatch.roadCard = it.roadCard
                busDispatch.startStationId = it.startStationId
                busDispatch.startStationName = it.startStationName
                busDispatch.startTime = it.startTime
                busDispatch.fjnr = it.fjnr
                busDispatch.ywlx = it.ywlx
                busDispatch.time = ""
            }*/

            busDispatch.ywlxName = when (busDispatch.ywlx) {
                1 -> "上行"
                2 -> "下行"
                3 -> "环行"
                else -> "其他"
            }
            busDispatch.ddlxName = when (busDispatch.ddlx) {
                1 -> "全程"
                2 -> "区间"
                3 -> "放站"
                else -> "其他"
            }

            busRepository.findLineById(busDispatch.line)?.let {
                busDispatch.lineName = it.name
            }

            busDispatch
        }
    }

    suspend fun listen8b07BusDispatch(): Flow<BusDispatch> {
        return jt808Flow.filter { (it is JT_8B07 && it.queueSize > 0) }.map {
            val busDispatch = BusDispatch()
            if (it is JT_8B07) {
                busDispatch.line = it.line
                busDispatch.ccbh = it.ccbh
                busDispatch.clbh = it.clbh
                busDispatch.ddlx = it.ddlx
                busDispatch.driverId = it.driverId
                busDispatch.driverName = it.driverName
                busDispatch.endStationId = it.endStationId
                busDispatch.endStationName = it.endStationName
                busDispatch.endTime = it.endTime
                busDispatch.roadCard = it.roadCard
                busDispatch.startStationId = it.startStationId
                busDispatch.startStationName = it.startStationName
                busDispatch.startTime = it.startTime
                busDispatch.fjnr = it.fjnr
                busDispatch.ywlx = it.ywlx
                busDispatch.time = ""
            }

            busDispatch.ywlxName = when (busDispatch.ywlx) {
                1 -> "上行"
                2 -> "下行"
                3 -> "环行"
                else -> "其他"
            }
            busDispatch.ddlxName = when (busDispatch.ddlx) {
                1 -> "全程"
                2 -> "区间"
                3 -> "放站"
                else -> "其他"
            }

            busRepository.findLineById(busDispatch.line)?.let {
                busDispatch.lineName = it.name
            }

            busDispatch
        }
    }

    suspend fun listen8B07(): Flow<ArrayList<BusPlan>> {
        return jt808Flow.filter { (it is JT_8B07 && it.queueSize > 0) }.map {
            var busDispatch = ArrayList<BusPlan>()
            if (it is JT_8B07) {
                busDispatch = it.arrayList
            }
            busDispatch
        }
    }

    /**
     * 查询主机状态信息
     */
    suspend fun queryDevState(): Result<DevState> {
        val ubusRet = Ubus.invoke(
            "bus",
            "query_state",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseDevState(ubusRet.rsp!!))
        }

        Log.debug("查询主机状态失败: ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 查询车辆行驶线路站点
     */
    suspend fun queryBusState(): Result<BusStateA> {
        val ubusRet = Ubus.invoke(
            "bus",
            "query_line_station",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseBusState(ubusRet.rsp!!))
        }

        Log.debug("查询车辆行驶线路站点失败: ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun download(sig: String, from: Long, to: Long): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_download",
            "{\"sig\":\"${sig}\",\"from\":\"${from}\",\"to\":\"${to}\"}"
        )
        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseFile(ubusRet.rsp!!))
        }

        Log.debug("下载段文件失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun queryGps(): Result<Location> {
        val ubusRet = Ubus.invoke(
            "gpsd",
            "gpsinfo",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseGps(ubusRet.rsp!!))
        }

        Log.debug("查询gps失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun send808(message: JT808Message): UResult {
        val uret = send808(message.messageType, JT808Help.encode(message))
        if (!uret.success) {
            Log.debug("send808 ${message.messageType} 失败")
        }
        return uret
    }

    private suspend fun send808(type: String, payload: String): UResult {
        val uResult = Ubus.invoke(
            "bus",
            "send808",
            "{\"type\":\"${type}\",\"payload\":\"${payload}\",\"sync\":false}"
        )
        android.util.Log.d("send808", "" + uResult.success + uResult.err + uResult.rsp)
        return uResult
    }

    private fun send808Sync(type: String, payload: String, timeout: Int = 1): Result<String> {
        val ubusRet = Ubus.invokeSync(
            "bus",
            "send808",
            "{\"type\":\"${type}\",\"payload\":\"${payload}\",\"sync\":true,\"timeout\":${timeout}}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取当前时间
     */
    suspend fun getTime(): Result<Long> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_date",
            ""
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseTime(ubusRet.rsp!!))
        }
        Log.debug("获取时间. ${ubusRet.err}")

        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取音量
     */
    suspend fun getDevVol(type: String): Result<DeviceVol> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"${type}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseGetVol(ubusRet.rsp!!))
        }

        Log.debug("获取音量失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取车辆信息
     */
    suspend fun getBusConfig(type: String): Result<BusConfig> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"${type}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseBusConfig(ubusRet.rsp!!))
        }
        Log.debug("获取车辆配置信息失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 设置音量
     */
    suspend fun setVol(in_vol: Int, out_vol: Int, mic_vol: Int): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"vol\",\"in_vol\":\"${in_vol * 10}\"" +
                    ",\"out_vol\":\"${out_vol * 10}\",\"mic_vol\":\"${mic_vol * 10}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("设置音量失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 查询摄像头文件夹列表
     */
    suspend fun queryCameraFile(): Result<CameraFileInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "query_video_list",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseCameraList(ubusRet.rsp!!))
        }

        Log.debug("查询视频文件失败. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * 查询摄像头文件列表
     */
    suspend fun queryCameraVideo(path: String): Result<CameraFileInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "query_video_dir_detail",
            "{\"path\":\"${path}\"}"
        )

        android.util.Log.d("copypathh", path)
        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseCameraList(ubusRet.rsp!!))
        }

        Log.debug("查询视频文件失败. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * 文件拷贝
     */
    suspend fun copyVideoFile(path: String): Result<String> {
/*
        val ubusRet = Ubus.invoke(
            "bus",
            "copy_file_list",
            "{\"list\":\"${path}\"}"
        )
*/

        val ubusRet = Ubus.invoke(
            "bus",
            "copy_file_list",
            "{\"list\":" + path + "}"
        )

        android.util.Log.d("ppppppayload", "{\"list\":" + path + "}")

        if (ubusRet.success) {
            return Result.Success((ubusRet.rsp!!))
        }

        Log.debug("copy文件失败. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * 管理员账号校验
     */
    suspend fun adminMakeSure(name: String, password: String): Result<Login> {
        val ubusRet = Ubus.invoke(
            "bus",
            "operation_request",
            "{\"name\":\"${name}\",\"password\":\"${password}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseLogin(ubusRet.rsp!!))
        }

        Log.debug("登录失败. ${ubusRet.err}")

        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * GPS地理信息
     */
    suspend fun queryGpsInfo(): Result<GpsInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_cur_gps",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseGpsInfo(ubusRet.rsp!!))
        }

        Log.debug("查询GPS信息. ${ubusRet.err}")

        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * 外部存储查询
     */
    suspend fun queryStorage(): Result<Storage> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_storage",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseStorage(ubusRet.rsp!!))
        }

        Log.debug("查询外部存储. ${ubusRet.err}")

        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * 服务器配置
     */
    suspend fun getNetConfig(type: String): Result<NetConfigInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"${type}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseNetconfig(ubusRet.rsp!!))
        }

        Log.debug("查询服务器配置. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    suspend fun getDevStatus(): Result<Boolean> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_bus_operating_state",
            ""
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseDevStatus(ubusRet.rsp!!))
        }

        Log.debug("查询服务器配置. ${ubusRet.err}")
        return Result.Error(java.lang.RuntimeException(ubusRet.err))
    }

    /**
     * 服务器配置
     * ubus call bus set_config '{"type":"servers", "payload":
     * "ip:192.168.10.6,tport:5000,uport:5001,vendor
     * :杭州公交,type:镜像服务器,protocol:808
     * ,platform_type:调度平台"}'
     */
    suspend fun setNetconfig(netConfig: NetConfig): Result<String> {
        var pinjie =
            "ip:" + netConfig.ip + ",tport:" + netConfig.tport + ",uport:" + netConfig.uport +
                    ",vendor:" + netConfig.vendor + ",type:" + netConfig.type + ",protocol:" + netConfig.protocol +
                    ",platform_type:" + netConfig.platform_type + ",action:add"
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"servers\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }


    /**
     * 服务器配置
     * ubus call bus set_config '{"type":"servers", "payload":
     * "ip:192.168.10.6,tport:5000,uport:5001,vendor
     * :杭州公交,type:镜像服务器,protocol:808
     * ,platform_type:调度平台"}'
     */
    suspend fun delNetconfig(netConfig: NetConfig): Result<String> {
        var pinjie =
            "ip:" + netConfig.ip + ",tport:" + netConfig.tport + ",uport:" + netConfig.uport +
                    ",vendor:" + netConfig.vendor + ",type:" + netConfig.type + ",protocol:" + netConfig.protocol +
                    ",platform_type:" + netConfig.platform_type + ",action:del"
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"servers\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 车辆信息
     */
    suspend fun queryBusInfo(): Result<BusInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"reginfo\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseBusInfo(ubusRet.rsp!!))
        }
        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun queryBasic(): Result<BasicInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"reginfo\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseBasicInfo(ubusRet.rsp!!))
        }
        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 无线网络信息
     */
    suspend fun queryWirelessInfo(): Result<Wireless> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"wireless\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseWireless(ubusRet.rsp!!))
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun setBusconfig(basicInfo: BasicInfo): Result<String> {
        var pinjie =
            "vdr_model:" + basicInfo.vdr_model + ",vdr_vendorid:" + basicInfo.vdr_vendorid + ",vid:" + basicInfo.vid +
                    ",simno:" + basicInfo.simno + ",car_num:" + basicInfo.car_num + ",car_color:" + basicInfo.car_color +
                    ",province_id:" + basicInfo.province_id + ",city_id:" + basicInfo.city_id + ",car_vin:" + basicInfo.car_vin +
                    ",sn:" + basicInfo.sn + ",dev_id:" + basicInfo.dev_id + ",car_id:" + basicInfo.car_id + ",line_id:" + basicInfo.line_id +
                    ",driver_id:" + basicInfo.driver_id + ",driver_name:" + basicInfo.driver_name
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"reginfo\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }


    /**
     * 配置按键语音
     */
    suspend fun setServiceAudio(key: Int): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_service_audio",
            "{\"key\":${key}}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun changeMicModel(type: Int): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_mic",
            "{\"mic\":\"open\",\"direct\":${type}}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun closeMic(type: Int): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_mic",
            "{\"mic\":\"close\",\"direct\":${type}}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取服务用语列表
     */
    suspend fun getServiceVoiceList(): Result<ServiceVoiceInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_service_audio_list",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseServiceVoiceList(ubusRet.rsp!!))
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 重播按键
     */
    suspend fun repeatPlayKey(): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_repeat_last_audio",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 播放
     */
    suspend fun playKey(): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_broadcast_audio",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 报警key
     */
    suspend fun alarmKey(): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_alarm",
            "{}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 自动手动切换
     * auto/manual
     */
    suspend fun autoKey(type: String): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_auto_manual_switch",
            "{\"type\":${type}}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 查询主机版本信息
     */
    suspend fun queryDevVersion(): Result<VersionInfos> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"version\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseDevVersion(ubusRet.rsp!!))
        }

        Log.debug("查询主机状态失败: ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun setUser(user: User, pwd: String, action: String): Result<String> {
        var pinjie =
            "type:" + user.type + ",name:" + user.name + ",password:" + pwd + ",action:" + action
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"user\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun getUser(): Result<UsersInfo> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"user\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseUser(ubusRet.rsp!!))
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }


    suspend fun reqUpdate(type: String): Result<String> {
        //主机升级：upgrade_bus  屏幕升级：upgrade_screen 重启：reboot_dev 恢复默认：restore_dev
        val ubusRet = Ubus.invoke(
            "bus",
            "req_device_upgrade",
            "{\"type\":\"${type}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun getSerialConfig(): Result<SerialInfo> {
        //主机升级：upgrade_bus  屏幕升级：upgrade_screen 重启：reboot_dev 恢复默认：restore_dev
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"serial\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseSerialList(ubusRet.rsp!!))
        }

        Log.debug("获取音量失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun setSerialConfig(data1: String, data2: String, data3: String,data4:String,data5: String): Result<String> {
        var pinjie =
            "232-1:$data1,232-2:$data2,232-3:$data3,485-1:$data4,485-2:$data5"
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"serial\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun getCANConfig(): Result<SerialInfo> {
        //主机升级：upgrade_bus  屏幕升级：upgrade_screen 重启：reboot_dev 恢复默认：restore_dev
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"can\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseCanList(ubusRet.rsp!!))
        }

        Log.debug("获取音量失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    suspend fun setCanConfig(data1: String, data2: String): Result<String> {
        var pinjie =
            "CAN1:$data1,CAN2:$data2"
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"can\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 时间配置
     * 2020-12-08_14:50:30
     */
    suspend fun setTimeConfig(
        time: String
    ): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"timing\",\"payload\":\"${time}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 自动校时设置
     */
    suspend fun setAutoTimeConfig(gps: String, ntp: String,host: String,server:String): Result<String> {
        var pinjie =
            "gps:$gps,ntp:$ntp,host:$host,server:$server"
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"auto_timing\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取自动校时配置
     */
    suspend fun getAutoTimeConfig(): Result<AutoTimingData> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"auto_timing\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseAutoTimingConfig(ubusRet.rsp!!))
        }

        Log.debug("获取音量失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取开火配置
     */
    suspend fun getFireConfig(): Result<FireData> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"onoff\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseFireConfig(ubusRet.rsp!!))
        }

        Log.debug("获取音量失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 开关点火配置
     */
    suspend fun setFireConfig(type: String, delaytime: String,start_time: String, end_time: String,back_light_time:String): Result<String> {
        var pinjie =
            "type:$type,delaytime:$delaytime,start_time:$start_time,end_time:$end_time,back_light_time:$back_light_time"
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"onoff\",\"payload\":\"${pinjie}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取摄像头配置
     */
    suspend fun getCameraConfig(): Result<CameraSettingsData> {
        val ubusRet = Ubus.invoke(
            "bus",
            "get_config",
            "{\"type\":\"camera\"}"
        )

        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseCameraConfig(ubusRet.rsp!!))
        }

        Log.debug("获取摄像头设置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 摄像头通道配置
     */
    suspend fun setCameraSettingConfig(payload: String):Result<String>{
        val ubusRet = Ubus.invoke(
            "bus",
            "set_config",
            "{\"type\":\"camera\",\"payload\":\"${payload}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("获取摄像头设置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 录入站点数据
     */
    suspend fun loadStationData(
        path: String,
        station: String
    ): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_record_station_gps",
            "{\"path\":\"${path}\",\"station\":\"${station}\"}"
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 导入站点数据
     */
    suspend fun importStationData(): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_import_lines_config",
            ""
        )

        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }

        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 导出站点数据
     */
    suspend fun exportStationData(): Result<String> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_export_lines_config",
            ""
        )
        if (ubusRet.success) {
            return Result.Success(ubusRet.rsp!!)
        }
        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }

    /**
     * 获取站点数据
     */
    suspend fun getStationData(
        path: String,
        station: String
    ): Result<LoadStationData> {
        val ubusRet = Ubus.invoke(
            "bus",
            "req_get_station_gps",
            "{\"path\":\"${path}\",\"station\":\"${station}\"}"
        )
        if (ubusRet.success) {
            return Result.Success(MessageHelp.parseStationGps(ubusRet.rsp!!))
        }
        Log.debug("配置失败. ${ubusRet.err}")
        return Result.Error(RuntimeException(ubusRet.err))
    }
}